package com.jzg.mvc.api.cabinet.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jzg.common.entity.Box;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabModuleFaultBox;
import com.jzg.common.model.biz.CabStore;
import com.jzg.common.model.biz.CabStoreBox;
import com.jzg.common.model.biz.CabStoreBoxLog;
import com.jzg.common.model.biz.CabUser;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.render.RenderLayuiBean;
import com.jzg.mvc.api.cabinet.CabController;


public class CabService{
	
	private static Prop propConfig = PropKit.use("app-config-dev.txt");
	
	public RenderLayuiBean listData(CabController cabController) {
		int pageNumber = cabController.getParaToInt("page", 1);
		int pageSize = cabController.getParaToInt("limit", 10);
		String userId = cabController.getPara("userId");
		String keyword = cabController.getPara("keyword");
		
		String sqlExceptSelect=" FROM "+Cab.TABLE_NAME+"  C,"+SysOrg.TABLE_NAME+" O  WHERE 1=1 AND C.ORGID=O.ID ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND O.NAME like '%" + keyword + "%' ";
		}
		if(!StrKit.isBlank(userId)) {
			sqlExceptSelect += " AND C.ORGID IN (SELECT ORGID FROM SYS_USER_ORG WHERE USERID='"+userId+"' ) ";
		}
		Page<Cab> page = Cab.dao.paginate(pageNumber, pageSize, "SELECT C.id,C.orgId,C.license,C.name NAME,O.NAME orgName ", sqlExceptSelect);
		List<Cab> cabs = page.getList();
		if(cabs!= null && cabs.size()>0) {
			for (Cab cab : cabs) {
				int used = Db.queryInt("select count(*) from "+CabStoreBox.TABLE_NAME+" where cabId=?",cab.getId());
				int fault = Db.queryInt("select count(*) from "+CabModuleFaultBox.TABLE_NAME+" where status='0' and cabId=?",cab.getId());
				int total = 0;
				Record record = Db.findFirst("select SUM(total) total from biz_cab_module where cabId=? ",cab.getId());
				if(!StrKit.isBlank(record.getStr("total"))) {
					total = record.getInt("total");
				}
				
				cab.setFaultNum(fault);
				cab.setUsedNum(used);
				cab.setFreeNum(total-fault-used);
				cab.setTotalNum(total);
				cab.setRoleStatus("1");
				CabUser cabUser = CabUser.dao.findFirst("select * from "+CabUser.TABLE_NAME+" where cabId=? and userId=? ",cab.getId(),userId);
				if(cabUser!=null && StrKit.equals(cabUser.getRoleKey(), "setting|")) {
					cab.setRoleStatus("0");
				}
				cabCaseHandle(cab);
			}
		}
		RenderLayuiBean renderBean=new RenderLayuiBean();
		renderBean.setCode(0);
		renderBean.setMsg("查询成功");
		renderBean.setData(page.getList());
		renderBean.setCount(page.getTotalRow());
		if(!propConfig.getBoolean("devMode")) {
			Record user = Db.use("plga").findFirst("select * from Manage WHERE NId = ?",userId);
			if(user!=null) {
				Record manaRole = Db.use("plga").findFirst("select * from ManaRole WHERE NId = ?",user.getInt("NGroup"));//201-00002
				if(manaRole!=null) {
					if(manaRole.getStr("SPermissions").contains(propConfig.get("uploadAuthCode"))) {
						renderBean.setAuth("1");
					}
					if(StrKit.equals("1", manaRole.getStr("NId"))) {
						renderBean.setAddAuth("1");
					}
				}
			}
		}
		return renderBean;
	}
	
	/**
	 * 柜子案件状态统计
	 * @param cab
	 */
	public void cabCaseHandle(Cab cab) {
		int caseNum=0;//总数
		int normalNum=0;//正常2
		int overdueNum=0;//超期-1
		int warnNum=0;//预警0
		int trialNum=0;//待审1
		int completeNum=0;//完成3
		SysOrg org = SysOrg.dao.findById(cab.getOrgId());
		if(org!=null) {
			List<CabStore>  stores = CabStore.dao.find("select * from "+CabStore.TABLE_NAME+" where cabId=? ",cab.getId());
			if(stores!=null && stores.size()>0) {
				caseNum = stores.size();
				for (CabStore cabStore : stores) {
					if(StrKit.equals("-1", cabStore.getStatus())) {
						overdueNum ++;
					}else if(StrKit.equals("0", cabStore.getStatus())) {
						warnNum ++;
					}else if(StrKit.equals("1", cabStore.getStatus())) {
						trialNum ++;
					}else if(StrKit.equals("2", cabStore.getStatus())) {
						normalNum ++;
					}else if(StrKit.equals("3", cabStore.getStatus())){
						completeNum ++;
					}else {
						if(StrKit.equals("53010305", org.getCODE())) {
							trialNum ++;
						}else {
							normalNum ++;
						}
					}
				}
			}
			if(StrKit.equals("53010305", org.getCODE())) {
				cab.setWaitingNum(trialNum);
			}else {
				cab.setNormalNum(normalNum);
			}
		}
		cab.setWarningNum(warnNum);
		cab.setCaseNum(caseNum);
		cab.setOverdueNum(overdueNum);
		cab.setFinishNum(completeNum);
	}
	
	/**
	 * 格子运行情况
	 * @param boxs
	 */
	public void boxStatus(List<Box> boxs,String caseNo) {
		for (Box box : boxs) {
			box.setBoxStatus("0");
			box.setCurrent(false);
			CabModuleFaultBox cabModuleFaultBox = 
				CabModuleFaultBox.dao.findFirst("select * from "+CabModuleFaultBox.TABLE_NAME+" where status='0' and boardId=? and boxNo=? ",box.getBoardId(),box.getSerialNo());
			if(cabModuleFaultBox!=null) {
				box.setBoxStatus("2");
			}else {
				CabStoreBox cabStoreBox = CabStoreBox.dao.findFirst("select * from "+CabStoreBox.TABLE_NAME+" where boardId=? and boxNo=? ",box.getBoardId(),box.getSerialNo());
				if(cabStoreBox!=null) {
					box.setBoxStatus("1");
					box.setCaseNo(cabStoreBox.getStoreId());
					if(!StrKit.isBlank(caseNo) && StrKit.equals(caseNo, cabStoreBox.getStoreId())) {
						box.setCurrent(true);
						box.setBoxStatus("3");
					}
				}
			}
		}
		
	}
	
	/**
	 * 格子运行情况
	 * @param boxs
	 */
	public void logBoxStatus(List<Box> boxs,String logId) {
		for (Box box : boxs) {
			box.setBoxStatus("0");
			box.setCurrent(false);
			CabModuleFaultBox cabModuleFaultBox = 
				CabModuleFaultBox.dao.findFirst("select * from "+CabModuleFaultBox.TABLE_NAME+" where status='0' and boardId=? and boxNo=? ",box.getBoardId(),box.getSerialNo());
			if(cabModuleFaultBox!=null) {
				box.setBoxStatus("2");
			}else {
				CabStoreBox cabStoreBox = CabStoreBox.dao.findFirst("select * from "+CabStoreBox.TABLE_NAME+" where boardId=? and boxNo=? ",box.getBoardId(),box.getSerialNo());
				if(cabStoreBox!=null) {
					box.setBoxStatus("1");
				}
				Map<String, String> actionStatus = getBoxActionMap(logId);
				String key = box.getBoardId()+"-"+box.getSerialNo();
				if(actionStatus.containsKey(key)) {
					box.setBoxStatus("3");
				}
			}
		}
		
	}
	
	/**
	 * 格子案件状态
	 * @param boxs
	 */
	public void boxCaseStatus(List<Box> boxs,String caseNo) {
		for (Box box : boxs) {
			if(StrKit.equals("1", box.getBoxStatus())) {
				box.setCaseStatus("0");
				CabStoreBox cabStoreBox = CabStoreBox.dao.findFirst("select * from "+CabStoreBox.TABLE_NAME+" where boardId=? and boxNo=? ",box.getBoardId(),box.getSerialNo());
				if(cabStoreBox!=null) {
					//box.setCaseStatus("1");
					CabStore cabStore = CabStore.dao.findFirst("select * from "+CabStore.TABLE_NAME+" where cabId=? and id=? ",cabStoreBox.getCabId(),cabStoreBox.getStoreId());
					if(cabStore!=null) {
						box.setCaseStatus(cabStore.getStatus());
					}else {
					}
					
				}
			}
		}
	}
	
	/**
	 * 查询预警平台获取案件状态
	 * @param caseNo
	 */
	public void getCaseStatus(String caseNo) {
		
	}
	
	/**
	 * 格子操作状态 0-打开1-存入2-取出
	 * @param boxs
	 */
	public void boxActionStatus(List<Box> boxs,String logId) {
		Map<String, String> actionStatus = getBoxActionMap(logId);
		for (Box box : boxs) {
			String key = box.getBoardId()+"-"+box.getSerialNo();
			if(actionStatus.containsKey(key)) {
				box.setActionStatus(actionStatus.get(key));
			}
		}
	}
	
	public Map<String, String> getBoxActionMap(String logId){
		List<CabStoreBoxLog> boxlogs =  CabStoreBoxLog.dao.find("select t.boardId,t.boxNo,max(t.`status`) status from biz_cab_store_box_log t where t.logId=? GROUP BY t.boardId,t.boxNo ",logId);
		Map<String, String> actionStatus = new HashMap<String, String>();
		if(boxlogs!=null && boxlogs.size()>0) {
			for (CabStoreBoxLog boxlog : boxlogs) {
				actionStatus.put(boxlog.getBoardId()+"-"+boxlog.getBoxNo(), boxlog.getStatus());
			}
		}
		return actionStatus;
	}
	
}
